package com.day02;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author 上官
 * @date 2024/7/6 21:41
 */
public class JsonReader {


    public static JSONObject jsonReader(String fileName) {
        // 加载classpath下的job.json
        URL resource = JsonReader.class.getClassLoader().getResource(fileName);
        try {
            URLConnection urlConnection = resource.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            byte[] by = new byte[inputStream.available()];
            inputStream.read(by);
            // 流转成文本
            String result = new String(by, "UTF-8");
            // 使用hutool解析json
            JSONObject jsonObject = JSONUtil.parseObj(result);
            // 一个树路径
            String path = "job.content[0].reader.parameter.connection[0].jdbcUrl[0]";
            // 获取值
            Object jsonValue= getValueFromJSON(jsonObject, path);
            System.out.println(jsonValue);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private static Object getValueFromJSON(JSONObject jsonObject, String path) {
        path = path.replace("[", ".[");
        String[] split = path.split("\\.");
        Object result = jsonObject;
        for (String indicate : split) {
            if (indicate.contains("[") && indicate.contains("]")) {
                if (result instanceof JSONArray) {
                    JSONArray temp = (JSONArray) result;
                    indicate = indicate.replaceAll("\\[|\\]", "");
                    result = temp.get(Convert.toInt(indicate));
                }
            } else {
                if (result instanceof JSONObject) {
                    JSONObject tempO = (JSONObject) result;
                    result = tempO.get(indicate);
                }
            }
        }

        return result;

    }


    public static void main(String[] args) {
        JsonReader.jsonReader("job.json");
    }
}
